package com.luo.backend.service;

import com.aliyun.oss.OSS;
import com.aliyun.oss.model.PutObjectRequest;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.io.InputStream;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.Arrays;
import java.util.List;
import java.util.UUID;

/**
 * 文件上传服务
 */
@Service
public class FileUploadService {

    private static final Logger logger = LoggerFactory.getLogger(FileUploadService.class);

    @Autowired
    private OSS ossClient;

    @Value("${aliyun.oss.bucketName}")
    private String bucketName;

    @Value("${aliyun.oss.urlPrefix}")
    private String urlPrefix;

    // 允许的图片类型
    private static final List<String> ALLOWED_EXTENSIONS = Arrays.asList(
            "jpg", "jpeg", "png", "gif", "webp"
    );

    // 最大文件大小：5MB
    private static final long MAX_FILE_SIZE = 5 * 1024 * 1024;

    /**
     * 上传图片到 OSS
     *
     * @param file 图片文件
     * @return 图片完整 URL
     * @throws Exception 上传失败异常
     */
    public String uploadImage(MultipartFile file) throws Exception {
        // 1. 验证文件是否为空
        if (file == null || file.isEmpty()) {
            throw new IllegalArgumentException("文件不能为空");
        }

        // 2. 验证文件大小
        if (file.getSize() > MAX_FILE_SIZE) {
            throw new IllegalArgumentException("图片大小不能超过5MB");
        }

        // 3. 获取原始文件名和扩展名
        String originalFilename = file.getOriginalFilename();
        if (originalFilename == null || originalFilename.isEmpty()) {
            throw new IllegalArgumentException("文件名不能为空");
        }

        String extension = getFileExtension(originalFilename);
        if (extension == null || !ALLOWED_EXTENSIONS.contains(extension.toLowerCase())) {
            throw new IllegalArgumentException("只支持图片文件（jpg、jpeg、png、gif、webp）");
        }

        // 4. 生成文件存储路径：foods/{年}/{月}/{日}/{UUID}.{扩展名}
        String filePath = generateFilePath(extension);

        // 5. 上传到 OSS
        try (InputStream inputStream = file.getInputStream()) {
            PutObjectRequest putObjectRequest = new PutObjectRequest(
                    bucketName,
                    filePath,
                    inputStream
            );
            ossClient.putObject(putObjectRequest);
            logger.info("图片上传成功：{}", filePath);
        } catch (IOException e) {
            logger.error("图片上传失败", e);
            throw new Exception("图片上传失败：" + e.getMessage());
        }

        // 6. 返回完整 URL
        String fullUrl = urlPrefix + "/" + filePath;
        logger.info("图片URL：{}", fullUrl);
        return fullUrl;
    }

    /**
     * 获取文件扩展名
     */
    private String getFileExtension(String filename) {
        int lastDotIndex = filename.lastIndexOf(".");
        if (lastDotIndex > 0 && lastDotIndex < filename.length() - 1) {
            return filename.substring(lastDotIndex + 1);
        }
        return null;
    }

    /**
     * 生成文件存储路径
     * 格式：foods/{年}/{月}/{日}/{UUID}.{扩展名}
     */
    private String generateFilePath(String extension) {
        LocalDateTime now = LocalDateTime.now();
        String year = now.format(DateTimeFormatter.ofPattern("yyyy"));
        String month = now.format(DateTimeFormatter.ofPattern("MM"));
        String day = now.format(DateTimeFormatter.ofPattern("dd"));
        String uuid = UUID.randomUUID().toString();

        return String.format("foods/%s/%s/%s/%s.%s", year, month, day, uuid, extension);
    }
}



